package com.java.shop.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.java.common.utils.PageUtils;
import com.java.common.utils.Query;
import com.java.shop.product.dao.AttrAttrgroupRelationDao;
import com.java.shop.product.dao.AttrGroupDao;
import com.java.shop.product.entity.AttrAttrgroupRelationEntity;
import com.java.shop.product.entity.AttrEntity;
import com.java.shop.product.entity.AttrGroupEntity;
import com.java.shop.product.service.*;
import com.java.shop.product.vo.AttrGroupWithAttrVo;
import com.java.shop.product.vo.AttrRelationVo;
import com.java.shop.product.webvo.SkuItemVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Slf4j
@Service("attrGroupService")
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService {
    @Autowired
    CategoryService categoryService;

    @Autowired
    AttrAttrgroupRelationService attrAttrgroupRelationService;

    @Autowired
    AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    @Autowired
    ProductAttrValueService productAttrValueService;


    @Autowired
    AttrService attrService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrGroupEntity> page = this.page(
                new Query<AttrGroupEntity>().getPage(params),
                new QueryWrapper<AttrGroupEntity>()
        );

        return new PageUtils(page);
    }


//    自己使用关联查询分类名，为了学习方便，使用老师同样的代码
//    @Override
//    public PageUtils myQueryPage(Map<String, Object> params, Long categoryId) {
//        if(categoryId == 0){
//            IPage<AttrGroupEntity> page = this.page(
//                    new Query<AttrGroupEntity>().getPage(params),
//                    new QueryWrapper<AttrGroupEntity>()
//            );
//            return new PageUtils(page);
//        }else {
//            QueryWrapper<AttrGroupEntity> wrapper = new QueryWrapper<>();
//            wrapper.eq("ag.catelog_id",categoryId);
//            String keys = (String) params.get("key");
//            if(!StringUtils.isEmpty(keys)){
//                wrapper.and(o -> {
//                    o.eq("ag.attr_group_id",keys).or().like("ag.attr_group_name",keys);
//                });
//            }
//            long curPage = 1;
//            long limit = 10;
//
//            if(params.get(Constant.PAGE) != null){
//                curPage = Long.parseLong((String)params.get(Constant.PAGE));
//            }
//            if(params.get(Constant.LIMIT) != null){
//                limit = Long.parseLong((String)params.get(Constant.LIMIT));
//            }
//            Page<AttrGroupEntity> page = new Page<>(curPage,limit);
//            return new PageUtils( baseMapper.getMyList(page,wrapper));
//        }
//    }


    @Override
    public void updateDetails(AttrGroupEntity attrGroup) {
        this.updateById(attrGroup);
        //TODO 若有其他表相连可以更新
    }

    @Override
    public PageUtils myQueryPage(Map<String, Object> params, Long categoryId) {
        QueryWrapper<AttrGroupEntity> wrapper = new QueryWrapper<>();
        if(categoryId != 0) wrapper.eq("catelog_id",categoryId);
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            wrapper.and(item->{
                item.eq("attr_group_id",key).or().like("attr_group_name",key);
            });
        }
        IPage<AttrGroupEntity> page = this.page(
            new Query<AttrGroupEntity>().getPage(params),wrapper
        );
        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params, Long categoryId) {
        if(categoryId == 0){
            IPage<AttrGroupEntity> page = this.page(
                    new Query<AttrGroupEntity>().getPage(params),
                    new QueryWrapper<AttrGroupEntity>()
            );
            return new PageUtils(page);
        }else{
            QueryWrapper<AttrGroupEntity> wrapper = new QueryWrapper<>();
            wrapper.eq("catelog_id",categoryId);

            Object keys = params.get("key");
            if(!StringUtils.isEmpty(keys)){
                wrapper.and(o -> {
                    o.eq("attr_group_id",keys).or().like("attr_group_name",keys);
                });
            }
            IPage<AttrGroupEntity> page = this.page(new Query<AttrGroupEntity>().getPage(params),wrapper);
            return new PageUtils(page);
        }
    }

    @Override
    public List<AttrEntity> getRelationAttr(Long attrGroupId) {
        List<AttrAttrgroupRelationEntity> relationList = attrAttrgroupRelationService.list(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrGroupId));
        if(relationList.size() == 0) return null;
        List<Long> attrIdList = relationList.stream().map(item -> item.getAttrId()).collect(Collectors.toList());
        return attrService.listByIds(attrIdList);
    }

    @Override
    public void deleteBatchRelation(List<AttrRelationVo> attrRelationVo) {
        attrAttrgroupRelationDao.deleteBatchRelation(attrRelationVo);
    }

    @Override
    public void saveBatchRelation(List<AttrRelationVo> attrRelationVo) {
        //判断关联的时候，关联表中是否已存在attrid，存在就更新，不存在就添加
        if(attrRelationVo.size() == 0) return;
        for(AttrRelationVo vo:attrRelationVo){
            Integer attrCount = attrAttrgroupRelationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", vo.getAttrId()));
            AttrAttrgroupRelationEntity relationVo = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(vo,relationVo);
            if(attrCount > 0){
                // 执行更新操作
                attrAttrgroupRelationDao.update(relationVo,new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", vo.getAttrId()));
            }else{
                // 执行添加操作
                attrAttrgroupRelationDao.insert(relationVo);
            }
        }
        // attrAttrgroupRelationDao.saveBatchRelation(attrRelationVo);
    }

    /**
     * 根据分类id查询分类下面对应的分组和分组下面的属性
     * @param catelogId
     * @return
     */
    @Override
    public List<AttrGroupWithAttrVo> getGroupWithAttr(Long catelogId) {
        //1.通过分类id查询分类下的属性分组
        QueryWrapper<AttrGroupEntity> wr = new QueryWrapper<>();
        wr.eq("catelog_id",catelogId);
        List<AttrGroupEntity> groupList = this.list(wr);

        //2.通过分组与属性关联表查询符合条件的属性
        if(groupList != null && groupList.size() != 0){
            return groupList.stream().map(groupEntity->{
                //2.1将查询的属性赋值给返回的vo
                AttrGroupWithAttrVo vo = new AttrGroupWithAttrVo();
                BeanUtils.copyProperties(groupEntity,vo);

                //2.2装配vo里面的attrs
                //2.2.1通过关联表查询
                Long attrGroupId = groupEntity.getAttrGroupId();
                List<AttrAttrgroupRelationEntity> relationList = attrAttrgroupRelationService.list(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrGroupId));
                if(relationList.size() != 0){
                    List<AttrEntity> collect = relationList.stream().map(relationEntity -> {
                        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
                        wrapper.eq("attr_id", relationEntity.getAttrId());
                        wrapper.eq("catelog_id", catelogId);
                        return attrService.getOne(wrapper);
                    }).collect(Collectors.toList());
                    vo.setAttrs(collect);
                }
                return vo;
            }).collect(Collectors.toList());
        }
        return null;
    }

    /**
     * 获取spu分组和分组下的所有属性名和属性值
     * @param spuId
     * @param catalogId
     * @return
     */
    @Override
    public List<SkuItemVo.SpuItemAttrGroupVo> getAttrGroupWithAttrsBySpuId(Long spuId, Long catalogId) {
        return baseMapper.getAttrGroupWithAttrsBySpuId(spuId,catalogId);
    }
}